package group;

import org.omg.CORBA.PRIVATE_MEMBER;
import vo.Product;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class groupByTest {

    private static List<Product> list = new ArrayList<>();

    static {

        Product prod1 = new Product(1L, 1, new BigDecimal("15.5"), "面包", "零食");
        Product prod2 = new Product(2L, 2, new BigDecimal("20"), "饼干", "零食");
        Product prod3 = new Product(3L, 3, new BigDecimal("30"), "月饼", "零食");
        Product prod4 = new Product(4L, 3, new BigDecimal("10"), "青岛啤酒", "啤酒");
        Product prod5 = new Product(5L, 10, new BigDecimal("15"), "百威啤酒", "啤酒");
        list.add(prod1);
        list.add(prod2);
        list.add(prod3);
        list.add(prod4);
        list.add(prod5);
    }


    /**
     * 属性拼接分组
     */
    public static void test1() {
        Map<String, List<Product>> collect = list.stream().collect(Collectors.groupingBy(item -> item.getCategory() + "_" + item.getName()));
        System.out.println(collect);
    }

    /**
     * 不同条件分组
     */
    public static void test2() {
        Map<String, List<Product>> collect = list.stream().collect(Collectors.groupingBy(item -> {
            if (item.getNum() < 3) {
                return "3";
            } else {
                return "other";
            }
        }));

        System.out.println(collect);
    }

    /**
     * 多级分组
     */
    public static void test3() {
        Map<String, Map<String, List<Product>>> collect = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.groupingBy(item -> {
            if (item.getNum() < 3) {
                return "3";
            } else {
                return "other";
            }
        })));

        System.out.println(collect);
    }

    /**
     * 子组收集数据 - 求总数 求和
     *
     */
    public static void test4() {
        Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));
        System.out.println(collect);

        System.out.println(list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summarizingInt(Product::getNum))));

    }

    public static void test5() {
        Map<String, Set<String>> collect = list.stream().
                collect(Collectors.groupingBy(Product::getCategory, Collectors.mapping(Product::getName, Collectors.toSet())));

        System.out.println(collect);
    }


    public static void main(String[] args) {
        test5();
    }

}
